package ejb.manager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import ejb.dao.ImageDAO;
import ejb.entity.DBImage;
import ejb.entity.DefaultDBImage;

@Stateless
public class DefaultDBImageManager implements DBImageManager {
	@EJB
	private ImageDAO imagedao;
	
	@Override
	public DBImage save(String name, byte[] data, String contentType){	
		DBImage image = new DefaultDBImage(name, data, contentType);
		image = imagedao.create(image);
		return image;
	}
	
	@Override
	public DBImage saveFromFile(String name, String path, String contentType){
		File file = new File(path);		
		try {
			FileInputStream fis = new FileInputStream(file);
			byte[] img = new byte[(int)file.length()];
			fis.read(img);
			DBImage image = new DefaultDBImage(name, img, contentType);
			image = imagedao.create(image);
			return image;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			System.err.println("Problem with creating FileInputStream!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.err.println("Problem with creating byte array!");
		}
		return null;
	}
	
	@Override
	public DBImage getImage(String name){
		DBImage image = imagedao.getImageByName(name);
		return image;
	}
	
	@Override
	public boolean delete(String name){
		DBImage image = imagedao.getImageByName(name);
		return imagedao.delete(image);		
	}
	
}
